<template>
  <div class="stations">
    <div
      class="SettingMask"
      v-show="showSettings"
      @click.self="showSettings = !showSettings"
    >
      <div class="settinngPanel">
        <van-cell-group inset>
          <van-cell center title="Station模式">
            <template #right-icon>
              <van-switch
                :model-value="checked"
                size="24"
                @update:model-value="onUpdateModel"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </div>

    <div class="header">
      <div class="addStation">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-zengjia"></use>
        </svg>
        <span>Add Station</span>
      </div>
      <div class="setting" @click="showSettings = !showSettings">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-shezhi"></use>
        </svg>
      </div>
    </div>
    <div class="stationItems">
      <van-swipe
        :loop="false"
        style="height: 100px"
        vertical
        :show-indicators="false"
        @change="onChange"
      >
        <van-swipe-item
          :class="{ isActive: isActive == index }"
          v-for="(item, index) in stationState.stations"
          :key="item"
          ><div class="sanjiao"></div>
          <div :class="{ isOverflow: isOverflow && isActive == index }">
            <span>{{ item.name }}</span>
            <div class="mask">
              <div class="cover"></div>
              <div class="cover"></div>
            </div>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="controlPanel">
      <div class="control">
        <van-slider
          v-model="pgValue"
          active-color="rgb(255, 255, 240)"
          button-size="0"
          inactive-color="rgba(255, 255, 255,.4)"
          bar-height=".1rem"
          style="border-radius: 0"
        />
        <div class="info">
          <div class="cover">
            <img
              :src="`http://121.36.209.69:4533/rest/getCoverArt?u=JensenWang&t=5eae806b5d0a4f1120b28c04a6f63801&s=22f91f&f=json&v=1.8.0&c=NavidromeUI&id=${
                nowAlbumSongs[store.state.stationPlayIndex]?.coverArt
              }&_=2022-09-03T12%3A33%3A00.813383978Z&size=300`"
              alt=""
            />
          </div>
          <div class="right">
            <h3>{{ nowAlbumSongs[store.state.stationPlayIndex]?.title }}</h3>
            <h4>{{ nowAlbumSongs[store.state.stationPlayIndex]?.artist }}</h4>
          </div>
        </div>
        <div class="bottom">
          <span>
            <svg aria-hidden="true">
              <use xlink:href="#icon-zan"></use>
            </svg>
          </span>
          <span class="cai">
            <svg aria-hidden="true">
              <use xlink:href="#icon-zan"></use>
            </svg>
          </span>
          <span>
            <svg
              aria-hidden="true"
              @click="playPause"
              v-show="store.state.stationIsPlaying"
            >
              <use xlink:href="#icon-zanting1"></use>
            </svg>
            <svg
              aria-hidden="true"
              v-show="!store.state.stationIsPlaying"
              @click="playPause"
            >
              <use xlink:href="#icon-bofang2-copy"></use>
            </svg>
          </span>
          <span>
            <svg aria-hidden="true" @click="playNext">
              <use xlink:href="#icon-next-fill"></use>
            </svg>
          </span>
        </div>
      </div>
    </div>
    <h1>{{}}</h1>
    <!-- <h1>{{nowAlbumSongs[store.state.stationPlayIndex]}}</h1> -->
    <audio
      ref="stationAudioPlayer"
      :src="`http://121.36.209.69:4533/rest/stream?u=JensenWang&t=60c93eef40f068e2ce2fa825eac35b77&s=c19b2d&v=1.12.0&c=MyTestApp&id=${
        nowAlbumSongs[store.state.stationPlayIndex]?.id
      }`"
    ></audio>
  </div>
</template>

<script setup>
const { ref, reactive } = require("@vue/reactivity");
const { watch, onMounted, computed } = require("@vue/runtime-core");
const { Dialog } = require("vant");
const { useRouter } = require("vue-router");
const { useStore } = require("vuex");
const router = useRouter();
const store = useStore();
import StationAPI from "@/request/api/stationsUtil";

//每次进入stations模式的时候就更新全局状态
store.commit("updateStationMode", true);
//stations模式标识
const checked = computed(() => {
  return store.state.isStationMode;
});
//设置标识
const showSettings = ref(false);
const onUpdateModel = (newValue) => {
  Dialog.confirm({
    title: "提示",
    message: "是否退出Station模式？",
  })
    .then(() => {
      // checked.value = newValue;
      store.commit("updateStationMode", false);
      let metas = document.getElementsByTagName("meta");
      metas["theme-color"].content = "#d8402f;";
      router.replace("/");
    })
    .catch(() => {
      showSettings.value = false;
    });
};

//判断是staion名字长度是否过长，开启滚动
let isOverflow = ref(false);
function checkOverflow(index) {
  let el = document.querySelectorAll(".van-swipe-item")[index];

  var curOverflow = el.style.overflow;

  if (!curOverflow || curOverflow === "visible") el.style.overflow = "hidden";
  //先让溢出效果为 hidden 这样才可以比较 clientHeight和scrollHeight
  var isOverflowing =
    el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
  el.style.overflow = curOverflow;
  return isOverflowing; //不满返回false
}

//更新当前播放时间定时器
let stationTimer = "";
let currentTime = ref(0);
let duration = ref(0);
function updateTime() {
  stationTimer = setInterval(() => {
    currentTime.value = stationAudioPlayer.value.currentTime;
    duration.value = stationAudioPlayer.value.duration;
  }, 1000);
}

//进度条绑定值
let pgValue = computed(() => {
  return (currentTime.value / duration.value) * 100;
});

//播放暂停控制
const stationAudioPlayer = ref(null);
function playPause() {
  if (stationAudioPlayer.value.paused) {
    stationAudioPlayer.value.play();
    store.commit("updateStationIsPlaying", true);
    duration.value = stationAudioPlayer.value.duration;
    updateTime();
  } else {
        // 暂停清除定时器
    clearInterval(stationTimer);
    stationAudioPlayer.value.pause();
    store.commit("updateStationIsPlaying", false);
  }
}
// 下一首
function playNext() {
  store.commit("playNext");
}
//自动播放下一首
watch(currentTime, () => {
  if (currentTime.value == duration.value) {
    updateIndex();
  }
});



//stations相关
let stations = ref([])
let stationState = reactive({
  stations: [],
  currentIndex: 0,
});

function saveStationState(stations, index) {
  localStorage.setItem("stationState", JSON.stringify(stationState));
}

async function getAlbumList() {
  let res = await StationAPI("getAlbumList");
  stationState.stations = res.data["subsonic-response"]["albumList"]["album"];
  getAlbum(stationState.stations[0].id);
  saveStationState();
}

//获取Album以及stations
let nowAlbumSongs = ref([]);
async function getAlbum(id) {
  let res = await StationAPI("getAlbum", id);
  nowAlbumSongs.value = res.data["subsonic-response"]["album"]["song"];
  store.commit(
    "updatStationNowAlbumSongs",
    res.data["subsonic-response"]["album"]["song"]
  );
  stationAudioPlayer.value.autoplay = true;
  updateTime();
}

//当前stations，以及切换相关操作
let isActive = ref(0);
const onChange = (index) => {
  isActive.value = index;
  getAlbum(stationState.stations[index].id);
  stationState.currentIndex = index;
  saveStationState();
  if (stations.value.length > 1) {
    let a = checkOverflow(index);
    isOverflow.value = a;
  }
};

//读取本地缓存
function getLoaclStation() {
  let stationNowAlbumSongs1 = localStorage.getItem("stationNowAlbumSongs");
  let stationPlayIndex1 = localStorage.getItem("stationPlayIndex");
  let stationStateLocal = localStorage.getItem("stationState");
  if (stationNowAlbumSongs1 && stationPlayIndex1 && stationState) {
    {
      stationState.stations = JSON.parse(stationStateLocal)["stations"];
      stationState.currentIndex = JSON.parse(stationStateLocal)["currentIndex"];
      store.commit(
        "updatStationNowAlbumSongs",
        JSON.parse(stationNowAlbumSongs1)
      );
      nowAlbumSongs.value = JSON.parse(stationNowAlbumSongs1);
      store.commit("updateStationPlayIndex", JSON.parse(stationPlayIndex1));
      isActive.value = JSON.parse(stationStateLocal)["currentIndex"];
      stationAudioPlayer.value.autoplay = true;
      updateTime();
    }
  } else {
    getAlbumList();
  }
}

//挂载之后进行数据初始化
onMounted(() => {
  let metas = document.getElementsByTagName("meta");
  metas["theme-color"].content = "#7760c1";
  if (stations.value.length > 1) {
    let a = checkOverflow(0);
    isOverflow.value = a;
  }
  getLoaclStation();
});




</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.stations {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background-color: #7760c1;
  z-index: 6;
  .SettingMask {
    width: 100%;
    height: 90%;
    // background-color: aqua;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 4;
    margin-top: 1.2rem;
    .settinngPanel {
      position: absolute;
      width: 3rem;
      // height: 4rem;
      right: 0.2rem;
      top: -0.2rem;
      background-color: #fff;
      border-radius: 5px;
      padding: 10px;
    }
    .settinngPanel::after {
      content: "";
      position: absolute;
      right: 0.2rem;
      top: -9px;
      border: 5px solid transparent;
      border-bottom: 5px solid rgb(255, 255, 255);
    }
  }

  .header {
    width: 100%;
    height: 1.2rem;
    background-color: #7760c1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0.2rem;
    position: relative;
    z-index: 3;
    box-shadow: 2px 2px 6px rgba(61, 61, 61, 0.2);
    .addStation {
      color: rgb(236, 235, 235);
      font-weight: 600;
      display: flex;
      justify-content: center;
      align-items: center;
      svg {
        height: 0.6rem;
        width: 0.6rem;
      }
      span {
        padding-left: 0.1rem;
        font-size: 0.4rem;
      }
    }
    .setting {
      width: 0.6rem;
      height: 0.6rem;
      position: relative;
      svg {
        width: 100%;
        height: 100%;
        opacity: 0.7;
      }
    }
  }
  .stationItems {
    margin-top: 50%;
    position: relative;
    .van-swipe {
      // background-color: rgba(251, 251, 251, 1);
      overflow: visible;
      z-index: 0;
      .van-swipe-item {
        // width: 100%;
        // background:#fff;
        color: rgba(0, 0, 0, 0.3);
        font-size: 0.9rem;
        font-weight: 700;
        white-space: nowrap;
        padding-left: 0.2rem;
        display: flex;
        align-items: center;
        overflow: hidden;
      }
      .isActive {
        color: #fff;
        font-size: 1rem;
        display: flex;
        align-items: center;
        padding-left: 0;
        position: relative;
        .sanjiao {
          position: relative;
          width: 0.2rem;
          height: 0.2rem;
          border: 0.2rem solid transparent;
          border-left: 0.2rem solid black;
          z-index: 3;
        }

        .isOverflow {
          width: 100%;
          height: 100%;
          overflow: hidden;
          display: flex;
          align-items: center;
          position: relative;
          .mask {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            justify-content: space-between;
            .cover {
              width: 1rem;
              height: 100%;
              background-size: 100% 100%;
              background-repeat: no-repeat;
            }
            .cover:nth-child(1) {
              background: linear-gradient(90deg, #7760c1 10%, transparent);
            }
            .cover:nth-child(2) {
              background: linear-gradient(90deg, transparent 10%, #7760c1);
            }
          }
          span {
            animation: scrollLoop 20s infinite linear;
          }
        }
      }
    }
  }

  @keyframes scrollLoop {
    0% {
      transform: translateX(0%);
    }
    100% {
      transform: translateX(-100%);
    }
  }
  .controlPanel {
    width: 100%;
    position: fixed;
    background-color: #7760c1;
    bottom: 0;
    padding: 0 0.2rem;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .control {
      height: 2.5rem;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding-bottom: 0.2rem;
      .info {
        display: flex;
        .cover {
          width: 1.1rem;
          height: 1.1rem;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .right {
          padding: 0 0.4rem;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          h3 {
            color: rgb(231, 228, 228);
          }
          h4 {
            color: rgba(0, 0, 0, 0.5);
          }
        }
      }

      .bottom {
        display: flex;
        justify-content: space-between;
        padding: 0 0.2rem;
        span {
          width: 0.5rem;
          height: 0.5rem;
          svg {
            width: 100%;
            height: 100%;
            fill: #fff;
          }
        }
        .cai {
          transform: rotate(180deg);
        }
      }
    }
  }
}
</style>